import {endpoint} from '../../utils/util.js';
//获取应用实例
var app = getApp(), n = ''
Page({
    data: {
        dataUrl: '',
        dataImage: '',
        music: '',
        is_pic: '',
        preview: 0,
        imgUrl: '',
        is_phone: false,
    },
    onLoad: function (options) {
        console.info(options)
        var t = this
        wx.getSystemInfo({
            success: function (res) {
                let system = {
                    win: false,
                    mac: false,
                    x11: false
                }
                let pf = res.platform //android ios
                console.log(res.platform)
                let isPhone = true
                system.win = pf.indexOf("win") == 0 || pf.indexOf("Win") == 0
                system.mac = pf.indexOf("mac") == 0 || pf.indexOf("Mac") == 0
                system.x11 = (pf == "X11") || (pf.indexOf("Linux") == 0) || (pf.indexOf("linux") == 0)
                if (system.win || system.mac || system.x11) {
                    isPhone = false
                }
                console.log(isPhone)
                t.setData({
                    is_phone: isPhone
                })
            }
        })
        if (options.is_pic == 1) {
            var pic_url = JSON.parse(decodeURIComponent(options.url));
            console.log(pic_url)
            this.setData({
                dataUrl: pic_url,
                is_pic: decodeURIComponent(options.is_pic),
                dataImage: decodeURIComponent(options.image),
                music: decodeURIComponent(options.music),
                preview: options.preview
            })
        } else {
            this.setData({
                dataUrl: decodeURIComponent(options.url),
                is_pic: decodeURIComponent(options.is_pic),
                dataImage: decodeURIComponent(options.image),
                music: decodeURIComponent(options.music),
                preview: options.preview
            })
        }

    },

    onUnload: function () {
        n && n.abort()
    },
    goBack: function () {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    copyUrl: function () {
        wx.setClipboardData({
            data: this.data.dataUrl,
            success: function (a) {
                wx.showToast({
                    title: '复制成功',
                    duration: 1200
                });
            }
        });
    },
    copyPicUrl: function (o) {
        console.log('保存图片')
        let targetUrl = o.currentTarget.dataset.targeturl;
        console.log(targetUrl)
        wx.setClipboardData({
            data: targetUrl,
            success: function (a) {
                wx.showToast({
                    title: '复制成功',
                    duration: 1200
                });
            }
        });
    },

    download: function (targetUrl) {
        var t = this, e = endpoint.downloadPrefix + targetUrl; // 无法直接下载资源域下的资源，需要通过nginx中转一层
        if (targetUrl.match('kwimgs.com')) {
            e = targetUrl;
        }
        console.log("download:" + e)
        wx.showLoading({title: '保存中 0%'})
        (n = wx.downloadFile({
            url: e,
            success: function (o) {
                console.log(o.tempFilePath)
                wx.hideLoading(), wx.saveVideoToPhotosAlbum({
                    filePath: o.tempFilePath,
                    success: function (o) {
                        t.showToast('保存成功', 'success'), setTimeout(function () {
                            wx.setClipboardData({
                                data: '',
                            })
                            t.goBack()
                        }, 1e3)
                    },
                    fail: function (o) {
                        console.log(o)
                        t.showToast('保存失败')
                    }
                })
            },
            fail: function (o) {
                n = null, wx.hideLoading(), t.showToast('下载失败')
            }
        })).onProgressUpdate(function (o) {
            100 === o.progress ? '' : wx.showLoading({
                title: '保存中 ' + o.progress + '%'
            })
        })
    },
    postSave: function (o) {
        var t = this;
        let targetUrl = o.currentTarget.dataset.targeturl;
        console.log("postSave1:" + targetUrl)
        console.log(o)
        wx.getSetting({
            success: function (o) {
                o.authSetting['scope.writePhotosAlbum'] ? t.download(targetUrl) : wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: function () {
                        console.log("postSave2:" + targetUrl)
                        t.download(targetUrl)
                    },
                    fail: function (o) {
                        wx.showModal({
                            title: '提示',
                            content: '视频保存到相册需获取相册权限请允许开启权限',
                            confirmText: '确认',
                            cancelText: '取消',
                            success: function (o) {
                                o.confirm ? (wx.openSetting({
                                    success: function (o) {
                                    }
                                })) : ''
                            }
                        })
                    }
                })
            }
        })
    },
    allSave: function (o) {
        let list = o.currentTarget.dataset.list;
        console.log(list);
        list.forEach(element => {
            console.log(element)
            this.picSave(element)
        });
    },
    downloadPic: function (targetUrl) {
        var t = this, e = endpoint.downloadPrefix + targetUrl; // 无法直接下载资源域下的资源，需要通过nginx中转一层
        console.log("download:" + e)

        wx.showLoading({
            title: '保存中 0%'
        }), (

            n = this.getImg(e)

        )
    },
    postPicSave: function (o) {
        var t = this;
        let targetUrl = o.currentTarget.dataset.targeturl;
        console.log("postSave1:" + targetUrl)
        console.log(o)
        wx.getSetting({
            success: function (o) {
                o.authSetting['scope.writePhotosAlbum'] ? t.downloadPic(targetUrl) : wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: function () {
                        console.log("postSave2:" + targetUrl)
                        t.downloadPic(targetUrl)
                    },
                    fail: function (o) {
                        wx.showModal({
                            title: '提示',
                            content: '视频保存到相册需获取相册权限请允许开启权限',
                            confirmText: '确认',
                            cancelText: '取消',
                            success: function (o) {
                                o.confirm ? (wx.openSetting({
                                    success: function (o) {
                                    }
                                })) : ''
                            }
                        })
                    }
                })
            }
        })
    },
    picSave: function (url) {
        var t = this;
        console.log("picSave1:" + url)
        wx.getSetting({
            success: function (o) {
                o.authSetting['scope.writePhotosAlbum'] ? t.downloadPic(url) : wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: function () {
                        console.log("postSave2:" + url)
                        t.downloadPic(url)
                    },
                    fail: function (o) {
                        wx.showModal({
                            title: '提示',
                            content: '视频保存到相册需获取相册权限请允许开启权限',
                            confirmText: '确认',
                            cancelText: '取消',
                            success: function (o) {
                                o.confirm ? (wx.openSetting({
                                    success: function (o) {
                                    }
                                })) : ''
                            }
                        })
                    }
                })
            }
        })
    },
    //获取文件流图片
    getImg(url) {
        let that = this
        wx.request({
            url: url,
            responseType: 'arraybuffer', //将数据转为类似二进制数组的格式
            success: res => {
                //进行转码
                let url = 'data:image/png;base64,' + wx.arrayBufferToBase64(res.data)
                that.setData({
                    imgUrl: url
                })
                this.downloadImg(url)
            }
        })
    },
    //判断base64并下载图片
    downloadImg(imgUrl) {
        let that = this
        console.log(that.data)
        var save = wx.getFileSystemManager();
        var number = Math.random();

        console.log(imgUrl)
        //判断是否为base64
        if (this.data.imgUrl) {
            if (!that.data.is_phone) {
                var file_path = wx.env.USER_DATA_PATH + '/test' + number + '.png'
                var data = that.data.imgUrl.replace('data:image/png;base64,', '')
            } else {
                var file_path = wx.env.USER_DATA_PATH + '/test' + number + '.webp'
                var data = that.data.imgUrl.replace('data:image/png;base64,', '')
            }
            console.log(file_path)
            console.log(data)
            save.writeFile({
                filePath: file_path,
                data: data,
                encoding: 'base64',
                success: res => {
                    wx.saveImageToPhotosAlbum({ //保存为jpg格式到相册
                        filePath: file_path,
                        success: function (res) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000, //提示的延迟时间，单位毫秒，默认：2500
                            })
                        },
                        fail: function (err) {
                            wx.hideLoading()
                        }
                    })
                },
                fail: err => {
                    console.log(err)
                }
            })
        } else {
            wx.downloadFile({
                url: that.data.imgUrl,//图片的地址
                success: function (res) {
                    const tempFilePath = res.tempFilePath
                    console.log(tempFilePath)
                    wx.saveImageToPhotosAlbum({
                        filePath: tempFilePath,  //设置下载图片的地址
                        success: function () {
                            wx.hideLoading()
                            wx.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000, //提示的延迟时间，单位毫秒，默认：2500
                            })
                        },
                        fail: function (err) {
                            wx.hideLoading()
                        }
                    }).onProgressUpdate(function (o) {
                        100 === o.progress ? '' : wx.showLoading({
                            title: '保存中 ' + o.progress + '%'
                        })
                    })
                }
            })
        }
    },
    showToast: function (o) {
        var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 'none',
            n = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 1500
        wx.showToast({
            title: o,
            icon: t,
            duration: n
        })
    }
})
